package dbfactory

import (
	"pmservice/config"
	log "pmservice/logger"
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var dsn string

// ORM struct to holds the gorm pointer to db
type ORM struct {
	DB *gorm.DB
}

// Read global db config in config.yml
func readDBConfig() {
	dsn = config.Cfg.Gorm.ConnectionDsn
}

var orm *ORM

// Factory creates a db connection with the selected dialect and connection string
func Factory() *ORM {
	if orm != nil {
		return orm
	}

	readDBConfig()
	newLogger := logger.New(
		log.Logger(),
		logger.Config{
			SlowThreshold: time.Second,  // 慢 SQL 阈值
			LogLevel:      logger.Error, // Log level
			Colorful:      true,         // 彩色打印
		},
	)

	// Open DB
	database, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		panic("failed to connect database")
	}

	orm = &ORM{
		DB: database,
	}

	return orm
}
